package com.ssii.www.myproject.shiro.realms;

import com.ssii.www.myproject.common.util.MD5Utils;
import com.ssii.www.myproject.domain.Permission;
import com.ssii.www.myproject.domain.User;
import com.ssii.www.myproject.service.PermissionService;
import com.ssii.www.myproject.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class TestRealm extends AuthorizingRealm {


  @Autowired
  private UserService userService;

  @Autowired
  private PermissionService permissionService;

  /**
   *  授权方法
   * @param principalCollection
   * @return
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    //获取用户
    User user = (User) principalCollection.getPrimaryPrincipal();
    //根据用户id查询权限
    Long id = user.getId();
    List<Permission> permissions = permissionService.getByUserId(id);
    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    for (Permission permission : permissions) {
      simpleAuthorizationInfo.addStringPermission(permission.getSn());
    }
    return simpleAuthorizationInfo;
  }

  /**
   * 认证方法
   * @param authenticationToken
   * @return
   * @throws AuthenticationException
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    //获取登陆的用户名
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;
    String name = usernamePasswordToken.getUsername();
    //根据用户名查询用户信息
    User user = userService.getUserByName(name);
    //初步判断
    if (user==null){
      throw new UnknownAccountException(name);
    }
    //封装info对象
    Object principal = user;//传入用户对象，因为传入用户名则只能获取用户名
    Object hashedCredentials = user.getPassword();//凭证，即数据库中加了密的密码
    //ByteSource credentialsSalt = ByteSource.Util.bytes(MD5Utils.SALT);//盐值
    String realmName = getName();
    //public SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName)
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,hashedCredentials,realmName);
    return info;

  }

}
